--======================================================================
--（c）copyright 2015 175game.com All Rights Reserved
--======================================================================
-- filename: game.lua
-- author: lxt  created: 2015/12/28
-- descrip: 游戏的入口，大部分管理类的持有者，除了CControlManager的gControl
--======================================================================
local CLogicEnter = Import("logic/common/logic_enter").CLogicEnter
local CBehaviorManager = Import("logic/common/behavior_manager").CBehaviorManager
local CLoadingMgr = Import("logic/common/loading_manager").CLoadingMgr
local CProtocolManager = Import("logic/net/protocol_manager").CProtocolManager
local CNetManager = Import("logic/net/net_manager").CNetManager
local CDataManager = Import("logic/data/data_manager").CDataManager
local CUIManager = Import("logic/ui/base/ui_manager").CUIManager
local CTimeManager = Import("logic/common/timer_manager").CTimerManager
local EventSource = Import("logic/common/event_source").EventSource
local CommonEnum = Import("logic/base/common_enum").Enum
local CObjectManager = Import("logic/object/object_manager").CObjectManager
local CGameObjectManager = Import("logic/object/game_object_manager").CGameObjectManager
local CTipManager = Import("logic/modules/tip/tip_manager").CTipManager
local CSceneManager = Import("logic/common/scene_manager").CSceneManager
local CSdkManager = Import("logic/sdk/sdk_manager").CSdkManager
local CTaskManager = Import("logic/modules/task/task_manager").CTaskManager
local CTrackManager = Import("logic/modules/task/track_manager").CTrackManager
local CFightMgr = Import("logic/fight/fight_mgr").CFightMgr
local CSummonSceneMgr = Import("logic/modules/summon/summon_scene_mgr").CSummonSceneMgr
local CSummonMergeMgr = Import("logic/modules/summon/summon_merge_mgr").CSummonMergeMgr
local CGuideManager = Import("logic/modules/onoff/guide_manager").CGuideManager
local COpenFuncManager = Import("logic/modules/onoff/openfunc_manager").COpenFuncManager
local CAudioManager = Import("logic/audio").CAudioManager
local CVideoManager = Import("logic/common/video_manager").CVideoManager
local CControllerManager = Import("logic/common/controller_manager").CControllerManager
local CItemInfoManager = Import("logic/common/iteminfo_manager").CItemInfoManager
local CPlayManager = Import("logic/modules/play/play_manager").CPlayManager
local CCameraEffectManager = Import("logic/common/camera_effect_manager").CCameraEffectManager
local CAiManager = Import("logic/modules/ai/ai_manager").CAiManager
local CBuildingManager = Import("logic/modules/building/building_manager").CBuildingManager
local CMinmapManager = Import("logic/ui/pnl_pet_activity_map/minimap_manager").CMinmapManager
local CRedPointManager = Import("logic/modules/redpoint/red_point_manager").CRedPointManager
local CUpdateManager = Import("logic/modules/redpoint/active_tips_manager").CUpdateManager
local CStoryManager = Import("logic/modules/story/story_manager").CStoryManager
--local CSceneCameraManager = Import("logic/modules/story/scene_camera_manager").CSceneCameraManager
local COrgfightObjectManager = Import("logic/object/orgfight/orgfight_object_manager").COrgfightObjectManager
local CSpeechManager = Import("logic/modules/speech/speech_manager").CSpeechManager
local CStreetManager = Import("logic/modules/street/street_manager").CStreetManager
local GlobalEnum = Import("logic/base/global_enum").Enum
local NetStatusEnum = Import("logic/base/net_enum").Enum.NET_STATUS

local CChangeSceneManager = Import("logic/common/change_scene_manager").CChanageSceneManager
local CCacheManager = Import("logic/common/cache_manager").CCacheManager

local CSkillManager = Import("logic/modules/skill/skill_manager").CSkillManager

local CQualitySetupManager = Import("logic/common/quality_setup_manager").CQualitySetupManager

local CPreloadSceneAssetManager = Import("logic/common/preload_scene_asset_manager").CPreloadSceneAssetManager

local CFPSMonitorManager = Import("logic/common/fps_monitor_manager").CFPSMonitorManager
local CGeometryManager = Import("logic/fight/geometry_mgr").CGeometryManager
local CGalgameEffectManager = Import("logic/common/galgame_effect_manager").CGalgameEffectManager
local CTaskModeController = Import("logic/modules/task/task_mode_controller").CTaskModeController

CGame = class(CLogicEnter)
CGame.__name = "CGame"

CGame.Init = function(self)
	CLogicEnter.Init(self)

	CCacheManager:Init()
end

CGame.InitManager = function(self)
	self._cacheManager = CCacheManager
	
	-- enngine or resource
	self._resourceMgr = ResourceManager.Instance
	self._audioManager = CAudioManager:New()
	self._actionMgr = ActionManager.Instance
	self._loadSceneMgr = LoadSceneMgr.Instance
	self._videoManager = CVideoManager:New()

	self._timerManager = CTimeManager:New()
	self._behaviorMgr = CBehaviorManager:New()
	self._loadingMgr = CLoadingMgr:New()
	self._protocolMgr = CProtocolManager:New()
	self._netMgr = CNetManager:New()
	self._dataMgr = CDataManager:New()
	self._uiMgr = CUIManager:New()
	self._sdkManager = CSdkManager:New()
	self._summonSceneMgr = CSummonSceneMgr:New()
	self._summonMergeMgr = CSummonMergeMgr:New()
	self.__global_EventSource__ = EventSource:New()

	self._objectManager = CObjectManager:New()
	self._gameObjectManager = CGameObjectManager:New()
	self._tipManager = CTipManager:New()
	self._sceneManager = CSceneManager:New()
	self._keepAliveTimer = nil
	self._taskManager = CTaskManager:New()
	self._trackManager = CTrackManager:New()
	self._guideManager = CGuideManager:New()
	self._openFuncManager = COpenFuncManager:New()
	--self._onOffCloseUiTips = COnOffCloseUiTips:New()
	self._controllerManager = CControllerManager:New()
	self._iteminfoManager = CItemInfoManager:New()
	self._playManager = CPlayManager:New()
	self._cameraEffectManager = CCameraEffectManager:New()
	self._aiManager = CAiManager:New()
	self._buildingManager = CBuildingManager:New()
	self._redpointManager = CRedPointManager:New()
	self._activeTipsManager = CUpdateManager:New()
	
	self._orgFightObjManager = COrgfightObjectManager:New()

	self._minimapManager = CMinmapManager:New()

	self._storyManager = CStoryManager:New()
	self._speechManager = CSpeechManager:New()

	self._changeSceneManager = CChangeSceneManager:New()

	self._skillManager = CSkillManager:New()

	self._streetManager = CStreetManager:New()	

	self._qualitySetupManager = CQualitySetupManager:New()

	self._preloadSceneAssetManager = CPreloadSceneAssetManager:New()

	self._fpsMonitorManager = CFPSMonitorManager:New()
	self._geometryMgr = CGeometryManager:New()
	self._galgameEffectManager = CGalgameEffectManager:New()
	self._taskModeController = CTaskModeController:New()

	CFightMgr:Init()
	self._fightMgr = CFightMgr
	self._controllerManager:GetSavePowerHandler():InitSavePowerType(self)
	Screen.sleepTimeout = UnityEngine.SleepTimeout.NeverSleep -- 默认永不息屏
end

--服务器下发协议
CGame.OnSocket = function(self, funcName, args)
	self._protocolMgr:OnSocket(funcName, args)
end

CGame.OnConnectStatus = function(self, status, msg)
	self._netMgr:OnConnectStatus(status, msg)
end

CGame.GetBehaviorMgr = function(self)
	return self._behaviorMgr
end

CGame.GetLoadingMgr = function(self)
	return self._loadingMgr
end

CGame.GetProtocolMgr = function(self)
	return self._protocolMgr
end

CGame.GetNetMgr = function(self)
	return self._netMgr
end

CGame.GetDataMgr = function(self)
	return self._dataMgr
end

CGame.GetUIMgr = function(self)
	return self._uiMgr
end

CGame.GetCurrentScene = function(self)
	return self._sceneManager:GetCurrentScene()
end

CGame.GetTimeManager = function(self)
	return self._timerManager
end

CGame.GetActionMgr = function(self)
	return self._actionMgr
end

CGame.GetGuideMgr = function(self)
	return self._guideManager
end

CGame.GetOpenFuncMgr = function(self)
	return self._openFuncManager
end

CGame.GetObjMgr = function(self)
	return self._objectManager
end

CGame.GetGameObjectMgr = function(self)
	return self._gameObjectManager
end

CGame.GetTipMgr = function(self)
	return self._tipManager
end

CGame.GetSceneMgr = function(self)
	return self._sceneManager
end

CGame.GetTaskMgr = function(self)
	return self._taskManager
end

CGame.GetTrackMgr = function(self)
	return self._trackManager
end

CGame.GetSummonSceneMgr = function(self)
	return self._summonSceneMgr
end

CGame.GetSummonMergeMgr = function(self)
	return self._summonMergeMgr
end

CGame.GetFightMgr = function(self)
	return self._fightMgr
end

CGame.GetAudioManager = function(self)
	return self._audioManager
end

CGame.GetVideoManager = function(self)
	return self._videoManager
end

CGame.GetControllerMgr = function(self)
	return self._controllerManager
end

CGame.GetOnOffCloseUiTipsMgr = function(self)
	return self._onOffCloseUiTips
end

CGame.ChangeFightScene = function(self, mapId)
--	modify by xcb
--	self:GetObjMgr():Clear()
--	self:GetDataMgr():GetSceneData():ClearObjData()

	gGame:ChangeScene("fight", mapId)
end

CGame.SwitchHuntScene = function(self, sceneLogicName, mapId)
	self._changeSceneManager:ChangeSceneHunt(sceneLogicName, mapId)
end

CGame.ChangeScene = function(self, sceneLogicName, sceneResId, sceneLogicId, sceneType)
	--self._sceneManager:ChangeScene(sceneLogicName, sceneResId, sceneLogicId, sceneType)
	self._changeSceneManager:ChangeScene(sceneLogicName, sceneResId, sceneLogicId, sceneType)
end

CGame.GetItemInfoManager = function(self)
	return self._iteminfoManager
end

CGame.GetPlayMgr = function(self)
	return self._playManager
end

CGame.GetLoadSceneMgr = function(self)
	return self._loadSceneMgr
end

CGame.GetResourceMgr = function(self) 
	return self._resourceMgr
end 

CGame.GetCameraEffectMgr = function(self)
	return self._cameraEffectManager
end

CGame.GetSdkMgr = function(self)
	return self._sdkManager
end

CGame.GetAiMgr = function(self)
	return self._aiManager
end

CGame.GetBuildingMgr = function(self)
	return self._buildingManager
end

CGame.GetMinimapMgr = function(self)
	return self._minimapManager
end

CGame.GetRedPointMgr = function(self)
	return self._redpointManager
end

CGame.GetActiveTipsMgr = function(self)
	return self._activeTipsManager
end

CGame.GetOrgFightObjMgr = function(self)
	return self._orgFightObjManager
end

CGame.GetStoryMgr = function(self)
	return self._storyManager
end

CGame.GetSpeechMgr = function(self)
	return self._speechManager
end

CGame.GetChangeSceneMgr = function(self)
	return self._changeSceneManager
end

CGame.GetCacheMgr = function(self)
	return self._cacheManager
end

CGame.GetSkillMgr = function(self)
	return self._skillManager
end

CGame.GetStreetMgr = function(self)
	return self._streetManager
end

CGame.GetQualitySetupMgr = function(self)
	return self._qualitySetupManager
end

CGame.GetPreloadSceneAssetManager = function(self)
	return self._preloadSceneAssetManager
end

CGame.GetFpsMonitorManager = function(self)
	return self._fpsMonitorManager
end

CGame.GetGeometryMgr = function(self)
	return self._geometryMgr
end 

CGame.GetGalgameEffectManager = function(self)
	return self._galgameEffectManager
end

CGame.GetTaskModeController = function(self)
	return self._taskModeController
end 

CGame.Update = function(self)
	self._behaviorMgr:Update()
	-- 修改object update的层次
	--self._objectManager:Update()
	self._sceneManager:Update()
	self._controllerManager:Update()

	self._changeSceneManager:Update()

	self:AddExitButtonListener()

	self._preloadSceneAssetManager:Update()
end

CGame.LateUpdate = function(self)
	self._behaviorMgr:LateUpdate()
	self._sceneManager:LateUpdate()
	self._controllerManager:LateUpdate()
end

CGame.FixedUpdate = function(self)
	self._behaviorMgr:FixedUpdate()
	self._sceneManager:FixedUpdate()
	self._timerManager:Update()
	self._galgameEffectManager:FixedUpdate()
end

CGame.AddExitButtonListener = function(self) -- 对退出按键进行监听
	if Input.GetKeyDown(KeyCode.Escape) and (tostring(Application.platform) == tostring(RuntimePlatform.Android)) then
		if self._reconfirmDialog then
			self._reconfirmDialog:Destroy()
			self._reconfirmDialog = nil
		end

		local exitFun = function()
			self:OnApplicationQuit()
		end

		self._reconfirmDialog = self:GetUIMgr():OpenReconfirmDialog(TEXT("提示"), TEXT("灵游师，你真的确定要离开了吗？"), TEXT("取消"), nil, TEXT("确认"), exitFun, true, {isOnTop = true, isHideClose = true})
	end
end

CGame.OnLevelWasLoaded = function(self, level)
	self._behaviorMgr:OnLevelWasLoaded()
	--self._sceneManager:OnLevelWasLoaded(level)
	self._changeSceneManager:OnLevelWasLoaded(level)
end

CGame.OnLoadedPercent = function(self, currIndex, lastIndex)
	self:GetLoadingMgr():OnLoadedPercent(currIndex, lastIndex)
end


CGame.OnApplicationQuit = function(self)
	self._behaviorMgr:OnApplicationQuit()
	self._sceneManager:OnApplicationQuit()
	self._behaviorMgr:Clear()
	self._actionMgr:Clear()
	self._uiMgr:Clear()
	self._redpointManager:Clear()
	self._fpsMonitorManager:Clear()
	self._dataMgr:ClearAllData()
	self._summonSceneMgr:Clear()
	self._audioManager:ReleaseAllAudio()
	self._trackManager:Clear()
	--self._onOffCloseUiTips:Release()
	
	self._cacheManager:Clear()
	self._netMgr:Clear()
	Application.Quit()
end

-- 当游戏程序暂停时，如切到后台，锁屏等等
CGame.OnPause = function(self)
	-- print("CGame.OnPause")
	self._controllerManager:OnPause()
end

-- 当游戏程序恢复到前台时
CGame.OnResume = function(self)
	-- 如果断线了，尝试重连
	if not self._netMgr then return end
	if self._netMgr:GetNetStatus() ~= NetStatusEnum.Disconnected then return end
	if not self._netMgr:IsLoginSuccess() then return end

	self._netMgr:Reconnect()

	-- self:FightSceneReconnect()
end

-- 重登
CGame.ReLogin = function(self)
	self._uiMgr:Clear()
	self._dataMgr:ClearAllData()

	self:ChangeScene("login", 1000)
end

-- 跨服
CGame.Gohost = function(self)
	self._dataMgr:GetTradeData():ClearTradeData()
	self._dataMgr:GetItemData():ClearItemList()
end

-- CGame.FightSceneReconnect = function(self)
-- 	if self._sceneManager:isFightScene() then
-- 		gGame:GetAiMgr():Clear()
-- 		gGame:GetFightMgr():FightEnd()
-- 		self._sceneManager:GetCurrentScene():OnDestroy()
-- 	end
-- end

--开启心跳包
CGame.StartKeepAliveTimer = function (self)
	self:StopKeepAliveTimer()

	self._keepAliveTimer = gGame:GetTimeManager():AddTimer(CommonEnum.PER_HEART_BEAT_SECOND, function()
		gGame:GetProtocolMgr():askRpc("rpc_server_heartbeat")
	end)
end

--停止心跳包
CGame.StopKeepAliveTimer = function (self)
	if self._keepAliveTimer then
		gGame:GetTimeManager():RemoveTimer(self._keepAliveTimer)
		self._keepAliveTimer = nil
	end
end

--下面三个函数用来进行全局事件监听
CGame.FireGlobalEvent = function (self, name, ...)
	FireGlobalEvent(name, ...)
end

CGame.DelGlobalEvent = function (self, name, handler)
	DelGlobalEvent(name, handler)
end

CGame.HandleGlobalEvent = function (self, name, func)
	return HandleGlobalEvent(name, func)
end
